package com.carnation.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.bean.GroupMenu;
import com.carnation.bean.HeadMenu;
import com.carnation.utils.MenuRead;
import com.google.gson.Gson;


public class InitServlet extends HttpServlet{
	Logger logger = Logger.getLogger(InitServlet.class);
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		doPost(httpServletRequest, httpServletResponse);
	}
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		MenuRead menuRead = new MenuRead();
		List<HeadMenu> list = menuRead.getHeadMenuList();
		Map<String, List<GroupMenu>> map = new HashMap<String, List<GroupMenu>>();
		for (HeadMenu headMenu : list) {
			if(!map.containsKey(headMenu.getName())){
				List<GroupMenu> groupMenuList = menuRead.getGroupMenuByHeadName(headMenu.getName());
				map.put(headMenu.getName(), groupMenuList);
			}
		}
		Gson gson = new Gson();		
		Map<String, Object> result = new HashMap<String,Object>();
		result.put("head", list);
		result.put("content",map);
		String json = gson.toJson(result);
		httpServletResponse.setContentType("application/json;charset=utf-8");
		try{
			httpServletResponse.getWriter().write(json);
			httpServletResponse.getWriter().flush();
			httpServletResponse.getWriter().close();
		}
		catch(Exception e){
			logger.error("响应报文写出错", e);
		}
	}
}
